package com.liqing.movecomment.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liqing.movecomment.entity.User;
import com.liqing.movecomment.dao.UserDao;
import com.liqing.movecomment.entity.UserChangeDto;
import com.liqing.movecomment.entity.UserDTO;
import com.liqing.movecomment.enums.RedisConstant;
import com.liqing.movecomment.exception.CustomException;
import com.liqing.movecomment.exception.LdException;
import com.liqing.movecomment.service.UserService;
import com.liqing.movecomment.util.RedisUtils;
import com.liqing.movecomment.util.ThreadLocalUtils;
import com.liqing.movecomment.vo.UserRegisterVo;
import com.qcloud.cos.utils.Md5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;

@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
    //<editor-fold defaultstate="collapsed" desc="delombok">
    @SuppressWarnings("all")
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UserServiceImpl.class);
    //</editor-fold>
    @Resource
    private UserDao userDao;

    /**
     * 分页查询
     *
     * @param page  页码
     * @param size  页大小
     * @param level
     * @return 查询结果
     */
    @Override
    public PageInfo<User> queryAll(Integer page, Integer size, Integer level) {
        PageHelper.startPage(page, size);
        final LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        // 1是管理员，2是会员用户
        if (!ObjectUtils.isEmpty(level)) {
            wrapper.eq(User::getLevel, level);
        }
        List<User> list = this.userDao.selectList(wrapper);
        return new PageInfo<>(list);
    }

    @Override
    public User login(UserDTO userDTO) throws CustomException {
        User loginUser = null;
        String username = userDTO.getUsername();
        //  图像验证码
        String code = String.valueOf(userDTO.getCode());
        if (StringUtils.hasLength(username)) {
            // 校验图像验证码是否正确
            String redisCaptchaCode = RedisUtils.getString(RedisConstant.CAPTCHA + userDTO.getUuid());
            if (Objects.equals(code, redisCaptchaCode)) {
                // 前端传递过来的密码，需要进行加密后跟数据库中的密码做比对的
                String password = userDTO.getPassword();
                String md5Password = SecureUtil.md5(password);
                List<User> userList = userDao.selectList(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
                for (User user : userList) {
                    // 前端传递过来的密码加密后和数据库中的密文进行比对
                    if (Objects.equals(user.getPassword(), md5Password)) {
                        log.info("用户名密码登录成功,用户名{},密码{}", username, password);
                        loginUser = user;
                    }
                }
            } else {
                throw new CustomException("图像验证码错误");
            }
        }
        return loginUser;
    }

    /**
     * 新增数据
     *
     * @param userRegisterVo 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(UserRegisterVo userRegisterVo) {
        final User user = new User();
        BeanUtils.copyProperties(userRegisterVo, user);
        log.info("账号注册成功==》账号{},密码{}", user.getUsername(), user.getPassword());
        //设置user
        user.setIsDelete(0);
        user.setPassword(SecureUtil.md5(user.getPassword()));
        this.userDao.insert(user);
        return user;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer id) {
        return this.userDao.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 页大小
     * @return 查询结果
     */
    @Override
    public PageInfo<User> queryAll(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<User> list = this.userDao.selectList(null);
        return new PageInfo<>(list);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        this.userDao.updateById(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userDao.deleteById(id) > 0;
    }

    @Override
    public User updatePassword(UserChangeDto userChangeDto) {
        User localUser = (User) ThreadLocalUtils.get();
        final User user = userDao.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, localUser.getId()).eq(User::getPassword, SecureUtil.md5(userChangeDto.getOldPassword())));
        if (ObjectUtils.isEmpty(user)) {
            throw new LdException(600, "输入旧密码错误");
        }
        User user1 = new User();
        user1.setId(localUser.getId());
        user1.setPassword(SecureUtil.md5(userChangeDto.getNewPassword()));
        userDao.updateById(user1);
        return userDao.selectById(user1.getId());
    }
}
